import {handleActions as createReducer} from 'redux-actions'
import {
  add_todo_success, 
  load_todo_success, 
  remove_todo_success,
  modify_todo_success,
  modify_todo_filter,
  clear_todo_completed_success,
  modify_todo__edit_success,
  modify_todo__name_success
} from '../actions/todo.actions'
import {fromJS,setIn,getIn,mergeDeep,removeIn,updateIn} from 'immutable'

const initialState = fromJS({
  todos:[],
  filter:'all'
})

export default createReducer({
  [load_todo_success]:(state,action)=>{
    // setIn 1操作的数据2.属性3.属性的值设置为
    return setIn(state,['todos'],action.payload)
  },
  [add_todo_success]:(state,action)=>{
    return mergeDeep(state,{todos:[action.payload]})
  },
  [remove_todo_success]:(state,action)=>{
    let index = getIn(state,['todos']).findIndex(todo=>todo.id === action.payload)
    return removeIn(state,['todos',index])
  },
  [modify_todo_success]:(state,action)=>{
    let index = getIn(state,['todos']).findIndex(todo=>todo.id === action.payload.id)
    return updateIn(state,['todos',index],()=>action.payload)
  },
  [modify_todo_filter]:(state,action)=>{
    return setIn(state,['filter'],action.payload)
  },
  [clear_todo_completed_success]:(state,action)=>{
    let todos = getIn(state,['todos']).filter(todo=>!todo.isCompleted)
    return setIn(state,['todos'],todos)
    
  },
  [modify_todo__edit_success]:(state,action)=>{
    let index = getIn(state,['todos']).findIndex(todo=>todo.id === action.payload.id)
    return updateIn(state,['todos',index],()=>action.payload)
    
  },
  [modify_todo__name_success]:(state,action)=>{
    let index = getIn(state,['todos']).findIndex(todo=>todo.id === action.payload.id)
    return updateIn(state,['todos',index],()=>action.payload)
  }
},initialState)

/***
 *  接收到指令之后对数据进行处理
 * 
 */